package com.etp.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.sql.SQLOutput;
import java.util.*;
import java.util.List;

public class ProductInfoExtractor extends JFrame {
    private JTextField filePathField;
    private JButton btnSelectFile, btnStart, btnOpenDir, btnRechooseDir, btnExit;
    private JProgressBar progressBar;
    /**
     * 显示当前选中的目录的路径
     */
    private JTextField dirPathField;
    private File selectedExcelFile;
    //private File outputDir = new File(System.getProperty("user.home") + File.separator + "Documents");
    /**
     * 输出目录
     */
    private File outputDir;
    private static final String[] COLUMN_HEADERS = {"产品ID", "产品名称", "分类", "价格"};

    /**
     * 增加一个输出目录的配置
     */
    private static final String CONFIG_PATH = System.getProperty("user.home") + File.separator + ".app_config";

    public ProductInfoExtractor() {
        super("产品信息提取工具");

        /**
         * 加载输出目录
         */
        loadOutputDir();

        System.out.println("----------" + System.getProperty("user.home"));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(600, 250);
        setupUI();
    }

    private void setupUI() {
        //JPanel mainPanel = new JPanel(new BorderLayout(5,5));
        //JFrame frame = new JFrame("居中显示示例");
        //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel mainPanel = new JPanel(new GridLayout(5, 1, 5, 5));

        // 文件选择区域
        JPanel filePanel = new JPanel(new BorderLayout());
        filePathField = new JTextField(30);
        filePathField.setEditable(false);
        btnSelectFile = new JButton("选择Excel文件");
        btnSelectFile.addActionListener(this::selectExcelFile);
        filePanel.add(new JLabel("Excel文件路径:"), BorderLayout.WEST);
        filePanel.add(filePathField, BorderLayout.CENTER);
        filePanel.add(btnSelectFile, BorderLayout.EAST);


        // 功能按钮区域
        JPanel btnPanel = new JPanel(new GridLayout(1, 4, 5, 5));
        btnStart = new JButton("开始提取");
        btnStart.addActionListener(this::startExtraction);
        btnOpenDir = new JButton("打开目录");
        btnOpenDir.addActionListener(e -> openOutputDirectory());
        btnRechooseDir = new JButton("重选目录");
        btnRechooseDir.addActionListener(e -> chooseOutputDirectory());
        btnExit = new JButton("退出");
        btnExit.addActionListener(e -> System.exit(0));

        btnPanel.add(btnStart);
        btnPanel.add(btnOpenDir);
        btnPanel.add(btnRechooseDir);
        btnPanel.add(btnExit);

        mainPanel.add(filePanel, BorderLayout.CENTER);
        mainPanel.add(btnPanel, BorderLayout.SOUTH);

        // 输出目录显示：
        JPanel dirPanel = new JPanel(new BorderLayout());
        String absolutePath = outputDir.getAbsolutePath();
        dirPathField = new JTextField(absolutePath);
        dirPathField.setEditable(false);
        dirPanel.add(new JLabel("当前输出目录："),BorderLayout.WEST);
        dirPanel.add(dirPathField,BorderLayout.CENTER);
        // 将目录面板添加到主界面布局中（根据实际布局调整）
        mainPanel.add(dirPanel, BorderLayout.SOUTH);

        // 进度条区域
        progressBar = new JProgressBar(0, 100);
        progressBar.setStringPainted(true);
        progressBar.setPreferredSize(new Dimension(500, 100));
        progressBar.setVisible(false);
        mainPanel.add(progressBar, BorderLayout.SOUTH);

        add(mainPanel);

        this.setLocationRelativeTo(null);      // 居中显示控件
    }

    // 文件选择方法
    private void selectExcelFile(ActionEvent e) {
        JFileChooser chooser = new JFileChooser();
        chooser.setFileFilter(new FileNameExtensionFilter("Excel文件", "xls", "xlsx"));
        if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            selectedExcelFile = chooser.getSelectedFile();
            filePathField.setText(selectedExcelFile.getAbsolutePath());
        }
    }

    // 核心处理逻辑
    private void startExtraction(ActionEvent e) {
        if (selectedExcelFile == null) {
            JOptionPane.showMessageDialog(this, "请先选择Excel文件");
            return;
        }

        progressBar.setVisible(true);
        progressBar.setValue(0);

        Component parentComponent = this;

        SwingWorker<Void, Integer> worker = new SwingWorker<Void, Integer>() {
            List<Map<String, String>> products = new ArrayList<>();
            JsonResult jsonResult = new JsonResult();

            @Override
            protected Void doInBackground() throws Exception {

                try (Workbook workbook = new XSSFWorkbook(selectedExcelFile)) {

                    // 获取所有的Sheet名称列表
                    String[] sheetNameList = new String[workbook.getNumberOfSheets()];
                    for(int i =0; i < sheetNameList.length; i++) {
                        sheetNameList[i] = workbook.getSheetName(i);
                    }

                    // 用户选择Sheet[12](@ref)
                    String selectedSheet = (String) JOptionPane.showInputDialog(
                            parentComponent, "请选择要读取的工作表:",
                            "工作表选择", JOptionPane.PLAIN_MESSAGE,
                            null, sheetNameList, sheetNameList[0]);

                    if(selectedSheet != null) {
                        Sheet sheet = workbook.getSheet(selectedSheet);

                        /**
                         * 调用 excelHelper, 进行读取数据并写出到 PPT 文件
                         */
                        ExcelHelper excelHelper = new ExcelHelper(sheet,outputDir);

                        /**
                         * 执行读取 excel 并写入到 PPT 文档
                         */
                        jsonResult = excelHelper.execExcelToPPT();



                    }

                    /*Sheet sheet = workbook.getSheetAt(0);
                    int totalRows = sheet.getPhysicalNumberOfRows();

                    for (int i = 1; i < totalRows; i++) { // 跳过标题行
                        Row row = sheet.getRow(i);
                        if (row != null) {
                            Map<String, String> product = parseRow(row);
                            products.add(product);
                        }
                        int progress = (int) ((i * 100.0) / totalRows);
                        publish(progress);
                    }*/
                }
                return null;
            }

            @Override
            protected void process(List chunks) {
                int latestProgress = (int) chunks.get(chunks.size() - 1);
                progressBar.setValue(latestProgress);
                progressBar.setString("处理中: " + latestProgress + "%");
            }

            @Override
            protected void done() {
                try {
                    get(); // 捕获可能的异常
                    //saveResults(products);

                    /**
                     * 显示结果
                     */
                    int productCount = 0;
                    int imageCount = 0;
                    try {
                        JSONObject jsonObject = (JSONObject)jsonResult.getData();

                        productCount = jsonObject.getInt("productCount");
                        imageCount = jsonObject.getInt("imageCount");

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    JOptionPane.showMessageDialog(ProductInfoExtractor.this,
                            "成功提取 " + productCount + " 条产品信息！共有 " + imageCount + " 张图片!",
                            "完成", JOptionPane.INFORMATION_MESSAGE);
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(ProductInfoExtractor.this,
                            "处理失败: " + ex.getMessage(),
                            "错误", JOptionPane.ERROR_MESSAGE);
                } finally {
                    progressBar.setVisible(false);
                }
            }
        };
        worker.execute();
    }

    // Excel行数据解析
    private Map<String, String> parseRow(Row row) {
        Map<String, String> product = new HashMap<>();
        for (int i = 0; i < COLUMN_HEADERS.length; i++) {
            Cell cell = row.getCell(i, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
            product.put(COLUMN_HEADERS[i], getCellValue(cell));
        }
        return product;
    }

    // 单元格值获取
    private String getCellValue(Cell cell) {
        switch (cell.getCellType()) {
            case STRING: return cell.getStringCellValue().trim();
            case NUMERIC: return String.format("%.2f", cell.getNumericCellValue());
            default: return "";
        }
    }

    // 结果保存方法
    private void saveResults(List<Map<String, String>> products) {
        try (PrintWriter writer = new PrintWriter(new File(outputDir, "product_results.txt"))) {
            writer.println("总产品数: " + products.size());
            writer.println("分类统计:");

            products.stream()
                    .map(p -> p.get("分类"))
                    .distinct()
                    .forEach(category -> writer.println("- " + category));
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, "保存失败: " + ex.getMessage());
        }
    }

    // 目录操作方法
    private void chooseOutputDirectory() {
        JFileChooser chooser = new JFileChooser(outputDir);
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            outputDir = chooser.getSelectedFile();
            // 设置新的目录到配置文件
            saveOutputDir(outputDir);

            // 重新设置输出目录的显示
            dirPathField.setText(outputDir.getAbsolutePath());

            JOptionPane.showMessageDialog(ProductInfoExtractor.this,
                    "重选目录成功",
                    "提示", JOptionPane.INFORMATION_MESSAGE);

        }
    }

    private void openOutputDirectory() {
        try {
            Desktop.getDesktop().open(outputDir);
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, "无法打开目录: " + ex.getMessage());
        }
    }


    /**
     * 初始化配置文件,并配置默认的输出目录
     *
     * @author hwz 2025-05-04
     */
    private void initConfigFile() {
        /**
         * 先定义一个默认的目录，即是 用户文档目录下的一个outputResult 目录
         */
        File defaultOutputDir = new File(System.getProperty("user.home") + File.separator + "Documents","outputResult");

        try {
            File configFile = new File(CONFIG_PATH);
            if(!configFile.exists()) {
                configFile.createNewFile();

                // 同时写入默认的目录
                if(!defaultOutputDir.exists()) {
                    defaultOutputDir.mkdir();
                }
                saveOutputDir(defaultOutputDir);
            }

        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

    }

    /**
     * 保存输出目录
     * @author hwz 2025-05-04
     * @param dir
     */
    private void saveOutputDir(File dir) {
        Properties props = new Properties();
        //props.setProperty("output.dir",dir.getAbsolutePath());
        String path = FileUtil.getAbsolutePath(dir);
        System.out.println("path--------:" + path);
        path = path.replace("\\","/");
        props.setProperty("output.dir",path);
        System.out.println("path--------:" + path);
        props.setProperty("output.dir",path);


        try(FileOutputStream fos = new FileOutputStream(CONFIG_PATH)) {
            OutputStreamWriter osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8);
            props.store(osw,"保存输出目录");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 加载上次选择的目录
     * @author hwz 2025-05-04
     */
    private void loadOutputDir() {

        initConfigFile();         // 初始化配置文件

        Properties props = new Properties();
        try(InputStreamReader reader = new InputStreamReader(new FileInputStream(CONFIG_PATH), "UTF-8")) {
            props.load(reader);

            String outputDirStr = props.getProperty("output.dir");

            outputDir =  new File(outputDirStr);
        } catch (IOException e) {

        }
    }


    /**
     * 加载上次选择的目录
     * @author hwz 2025-05-04
     */
    private void loadOutputDir_bak() {

        initConfigFile();         // 初始化配置文件

        Properties props = new Properties();
        try(FileInputStream fis = new FileInputStream(CONFIG_PATH)) {
            props.load(fis);

            String outputDirStr = props.getProperty("output.dir");

            System.out.println("读取的目录是：" + new String(outputDirStr.getBytes(Charset.forName("utf-8"))));

            System.out.println("-=---outputDirStr---" + outputDirStr);
            outputDir =  new File(outputDirStr);
        } catch (IOException e) {

        }
    }

    /*public static void main(String[] args) {

        SwingUtilities.invokeLater(() -> {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception ignored) {}
            ProductInfoExtractor extrator = new ProductInfoExtractor();
            *//**
             * 初始化输出目录
             *//*
            extrator.setVisible(true);
        });
    }*/
}